package com.jiuzhou.surery.security;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jiuzhou.surery.beans.User;
import com.jiuzhou.surery.db.UserRepository;
 
@Service
@Transactional
public class SurveyUserDetailsManager implements UserDetailsManager {
    private final UserRepository userRepository;

    public SurveyUserDetailsManager(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new SurveyUserDetails(user, userRepository.getAuthorities(username));
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
         throw new UnsupportedOperationException("Unimplemented method 'changePassword'");
    }

    @Override
    public void createUser(UserDetails user) {
        SurveyUserDetails surveyUserDetails = (SurveyUserDetails) user;
        userRepository.save(surveyUserDetails.getUser());
        userRepository.addAuthorities(surveyUserDetails.getUsername(), surveyUserDetails.getAuthorities()); 
    }

    @Override
    public void deleteUser(String username) {
        userRepository.deleteByUsername(username);
        userRepository.deleteAuthority(username);
    }

    @Override
    public void updateUser(UserDetails user) {
        SurveyUserDetails surveyUserDetails = (SurveyUserDetails) user;
        userRepository.update(surveyUserDetails.getUser());
        userRepository.deleteAuthority(surveyUserDetails.getUsername());
        userRepository.addAuthorities(surveyUserDetails.getUsername(), surveyUserDetails.getAuthorities()); 
    }

    @Override
    public boolean userExists(String username) {
        try {
            User user = userRepository.findByUsername(username);
            return user != null;
        } catch (Exception e) {
            return false;
        }
    }
    
}
